<template>
  <el-dialog
    :title="dialogConfig.title"
    :visible.sync="dialogConfig.show"
    width="30%"
    :before-close="handleClose"
  >
    <el-upload
      class="upload-demo"
      drag
      action=""
      :file-list="fileList"
      :auto-upload="false"
      :on-remove="moveList"
      :on-change="uploadFile"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button v-if="tempConfig.show" @click="downLoadTemp">下载模板</el-button>
      <el-button type="primary" @click="handlerImportFn">导入</el-button>
    </span>
  </el-dialog>
</template>

<script>
// import { showUploadAlter } from '@/utils/fileActions'

export default {
  name: 'ImportFileDialog',
  props: {
    configParams: {
      type: Object,
      default: () => {
        return {}
      }
    }

  },

  data() {
    return {
      // 是否打开导入弹窗
      importDialogVisible: false,
      // 文件列表
      fileList: []
    }
  },
  computed: {
    dialogConfig() {
      const { dialogConfig = {}} = this.configParams || {}
      return Object.assign({}, {
        show: false,
        title: '导入弹窗'
      }, { ...dialogConfig })
    },
    importConfig() {
      const { importConfig = {}} = this.configParams || {}
      return Object.assign({}, {
        fileType: ['csv', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'],
        fileSize: '',
        uploadParams: null,
        uploadAPI: () => {},
        successFn: () => {}
      }, { ...importConfig })
    },
    tempConfig() {
      const { tempConfig = {}} = this.configParams || {}
      return Object.assign({}, {
        show: true,
        tempAPI: () => {},
        downParams: {}
      }, { ...tempConfig })
    }

  },
  watch: {
    dialogConfig: {
      immediate: true,
      deep: true,
      handler(newValue, oldValue) {

      }
    }
  },
  methods: {
    // 文件传入
    uploadFile(file, fileList) {
      const { raw, name } = file
      const checkRes = this.checkFileType(file)
      if (checkRes) {
        this.fileList = [{ name: name }]
        this.file = raw
      } else {
        this.fileList = []
      }
    },
    // 导入方法
    async handlerImportFn() {
      if (!this.file) return this.$message.error('请先选择文件')

      const { uploadAPI = () => {}, uploadParams = '', successFn = () => {} } = this.importConfig || {}
      const { size } = this.file
      // 100kb 15秒计算
      const timeout = size ? ((size / 1024) / 100) * 15 : 5
      try {
        const formData = new FormData()
        formData.append('file', this.file)
        uploadParams && formData.append('params', uploadParams)
        const uploadRes = await uploadAPI(formData, timeout)
        switch (uploadRes.code) {
          // todo
          case 31400:
            // showUploadAlter(uploadRes.result)
            break
          default:
            this.$message.success(uploadRes.msg || '全部导入成功')
            this.$set(this.configParams['dialogConfig'], 'show', false)
            successFn && successFn(uploadRes)
            break
        }
      } catch (error) {
        console.log('上传失败', error)
      }
    },
    //  移除文件
    moveList(file) {
      this.file = null
      this.fileList = []
      this.$set(this.configParams['dialogConfig'], 'show', false)
    },
    handleClose(done) {
      this.moveList()
      done()
    },
    // 下载模板
    async downLoadTemp() {
      const { tempAPI = () => {}, downParams = {}} = this.tempConfig || {}
      try {
        await tempAPI({
          ...downParams
        })
      } catch (error) {
        console.log('下载文件失败')
      }
    },

    // 检查文件类型
    checkFileType(file) {
      const { fileType, fileSize } = this.importConfig || {}
      const { type, size, name } = file
      if (type && !fileType.includes(type)) {
        this.$message.error('文件类型错误！')
        return false
      }
      // 如果type为空的情况, 判断名称
      if (!type) {
        const Type = name.split('.')
        if (!['xlsx', 'xls', 'csv'].includes(Type.pop())) {
          this.$message.error('文件类型错误！')
          return false
        }
      }
      if (fileSize) {
        return fileSize * 1024 * 1024 >= size
      }

      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-demo {
  width: 100%;
  /deep/.el-upload,
  /deep/.el-upload-dragger {
    @include relative();
    height: 200px;
  }
}
.dialog-footer {
  button {
    &:first-child {
      // float: left;
    }
  }
}
</style>
